// pages/goods_list/index.js
import { request } from '../../request/index'
import regeneratorRuntime from '../../lib/runtime/runtime';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [
      {
        id: 0,
        value: "综合",
        isActive: true
      },
      {
        id: 1,
        value: "销量",
        isActive: false
      },
      {
        id: 2,
        value: "价格",
        isActive: false
      }
    ],
    // 商品列表
    goodsList: [],
    // 总页数
    totalPages: 1
  },

  // 参数
  queryParams: {
    query: "",
    cid: "",
    pagenum: 1,
    pagesize: 10
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options);
    this.queryParams.cid = options.cid || ""
    this.queryParams.query = options.query || ""
    this.getGoodsList()
    // console.log(this.queryParams);
  },

  // 获取商品列表
  async getGoodsList () {
    const result = await request({ url: "/goods/search", data: this.queryParams })
    // console.log(result);
    // 总页数
    const total = result.total
    // console.log(total);
    this.setData({
      goodsList: [...this.data.goodsList, ...result.goods],
      totalPages: Math.ceil(total / this.queryParams.pagesize)
    })

    // 关闭下拉刷新的窗口 如果没有调用下拉刷新的窗口 直接关闭也不会报错  
    wx.stopPullDownRefresh();
  },

  // tab 栏切换
  handleTapChange (e) {
    // console.log(e);
    const { index } = e.detail
    let { tabs } = this.data
    tabs.forEach(v => v.id === index ? v.isActive = true : v.isActive = false)
    this.setData({
      tabs
    })
  },

  // ⻚⾯上拉触底事件的处理函数
  onReachBottom () {
    if (this.queryParams.pagenum >= this.data.totalPages) {
      // 没有数据
      wx.showToast({
        title: '已经到底了',
      })
    } else {
      this.queryParams.pagenum++
      this.getGoodsList()
    }
  },

  // 监听⽤⼾下拉动作
  onPullDownRefresh () {
    // 重置数组
    this.setData({
      goodsList: [],
    })
    // 重置页码
    this.queryParams.pagenum = 1
    // 发送请求
    this.getGoodsList()
  }

})